/**
 * Created by Handsome.Ho on 2015/9/19.
 */
angular.module('schedule.services', []).factory('Schedule', function () {
  /**
   * 计算是否闰年
   * @param year
   * @returns {boolean}
   */
  function isLeapYear(year) {
    var f = new Date();
    f.setYear(year);
    f.setMonth(1);
    f.setDate(29);
    return f.getDate() == 29;
  }

  /**
   * 计算二月份天数
   * @returns {*}
   */
  function febCalc(year) {
    var feb;
    if (isLeapYear(year) === true) {
      feb = 29;
    } else {
      feb = 28;
    }
    return feb;
  }

  /**
   * 计算日期 增加指定天数
   * @param d
   * @param dayNum
   * @returns {Date}
   */
  function addDay(d, dayNum) {
    var t = d.getTime() + 1000 * 60 * 60 * 24 * dayNum;
    return new Date(t);
  }

  /**
   * 计算日期 减去指定天数
   * @param d
   * @param dayNum
   * @returns {Date}
   */
  function minusDay(d, dayNum) {
    var t = d.getTime() - 1000 * 60 * 60 * 24 * dayNum;
    return new Date(t);
  }

  function dayString(date) {
    var dayStr = date + '';
    if (dayStr.length == 1) {
      dayStr = ' ' + date;
    }
    return dayStr;
  }

  var weeknames = new Array('日', '一', '二', '三', '四', '五', '六');

  var service = {
    weeknames: weeknames,
    getData: function (year, month) {
      var monthDays = new Array(31, febCalc(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
      var dayNum = monthDays[month - 1];
      var grid = new Array();
      var row = new Array();
      for (var i = 1; i <= dayNum; i++) {
        var date = new Date(year, month - 1, i);
        var weekday = date.getDay();
        if (i == 1) {
          for (j = 0; j < weekday; j++) {
            var preDate = minusDay(date, weekday - j);
            row.push({
              include: false,
              date: preDate,
              weekday: weeknames[j]
            });
          }
        }
        row.push({
          include: true,
          date: date,
          weekday: weeknames[weekday]
        });
        if (i == dayNum) {
          for (var j = weekday + 1; j <= 6; j++) {
            var afterDate = addDay(date, j - weekday);
            row.push({
              include: false,
              date: afterDate,
              weekday: weeknames[j]
            });
          }
          grid.push(row);
        } else if (weekday == 6) {
          grid.push(row);
          row = new Array();
        }
      }
      for(var i=0;i<grid.length;i++){
        for(var j=0;j<grid[i].length;j++){
          grid[i][j].weekindex = i;
        }
      }
      return grid;
    },
    getTask: function (sdt, edt, userid) {

    }
  };
  return service;
});
